// 权限控制
import router from './router'
import store from './store'
import asyncRouters from './router/asyncRouters'

const WHITE_LIST = ['/login', '/404']
//根据1级权限表示筛选出对应的权限标识
function getRoutes(firstPermission, asyncRouters) {
  //筛选第一级路由
  const firstRoutes = asyncRouters.filter(item => firstPermission.includes(item.permission))
  return firstRoutes
}

router.beforeEach(async (to, from, next) => {
  const token = store.state.user.token
  // 有token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      //拿到用户的权限信息
      const permission = await store.dispatch('menu/getUserPermission')
      const routers = getRoutes(permission, asyncRouters)
      //添加404的错误页面
      routers.push({
        path: '/*',
        component: () => import('@/views/404'),
        hidden: true
      }, )
      //添加进路由规则
      routers.forEach(item => router.addRoute(item))
      //把筛选出的路由添加到vuex中
      store.commit('menu/setMenuList', routers)
    }
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
